const multer = require('multer');
const path = require('path');
const fs = require('fs');
const { v4: uuidv4 } = require('uuid');
const Jimp = require('jimp');
const PDFDocument = require('pdfkit');
const imageUtils = require('../utils/imageUtils');

// 配置文件上传
const storage = multer.diskStorage({
  destination: (req, file, cb) => {
    cb(null, path.join(__dirname, '../public/uploads'));
  },
  filename: (req, file, cb) => {
    const uniqueName = `${Date.now()}-${uuidv4().substring(0, 8)}${path.extname(file.originalname)}`;
    cb(null, uniqueName);
  }
});

// 文件过滤器
const fileFilter = (req, file, cb) => {
  // 只接受图片文件
  if (!file.mimetype.startsWith('image/')) {
    return cb(new Error('只能上传图片文件'), false);
  }
  
  // 检查文件扩展名
  const allowedExtensions = ['.jpg', '.jpeg', '.png', '.gif'];
  const ext = path.extname(file.originalname).toLowerCase();
  if (!allowedExtensions.includes(ext)) {
    return cb(new Error('只支持JPG、PNG和GIF格式的图片'), false);
  }
  
  cb(null, true);
};

const upload = multer({ 
  storage,
  limits: { 
    fileSize: 5 * 1024 * 1024, // 限制5MB
    files: 1 // 一次只能上传一个文件
  },
  fileFilter
}).single('image');

// 上传图片
exports.uploadImage = (req, res) => {
  console.log('收到上传请求:', req.headers);
  
  // 确保uploads目录存在
  const uploadsDir = path.join(__dirname, '../public/uploads');
  if (!fs.existsSync(uploadsDir)) {
    fs.mkdirSync(uploadsDir, { recursive: true });
    console.log('创建uploads目录:', uploadsDir);
  }
  
  upload(req, res, (err) => {
    if (err) {
      console.error('上传处理错误:', err);
      
      if (err instanceof multer.MulterError) {
        // Multer错误
        if (err.code === 'LIMIT_FILE_SIZE') {
          return res.status(400).json({
            success: false,
            message: '文件大小超过限制（最大5MB）'
          });
        }
      }
      
      return res.status(400).json({
        success: false,
        message: err.message
      });
    }
    
    if (!req.file) {
      console.error('没有上传文件');
      return res.status(400).json({
        success: false,
        message: '没有上传文件'
      });
    }
    
    console.log('文件上传成功:', req.file);
    
    // 返回上传成功的文件信息
    const host = req.get('host');
    const protocol = req.protocol;
    const fullPath = `${protocol}://${host}/uploads/${req.file.filename}`;
    
    console.log('返回文件路径:', fullPath);
    
    res.status(200).json({
      success: true,
      message: '文件上传成功',
      data: {
        filename: req.file.filename,
        path: `/uploads/${req.file.filename}`,
        fullPath: fullPath
      }
    });
  });
};

// 处理图片（边缘检测、透视校正、增强）
exports.processImage = async (req, res) => {
  try {
    const { imagePath } = req.body;
    
    if (!imagePath) {
      return res.status(400).json({
        success: false,
        message: '缺少图片路径'
      });
    }
    
    // 获取完整的文件路径
    const fullPath = path.join(__dirname, '../public', imagePath.replace(/^\//, ''));
    
    // 检查文件是否存在
    if (!fs.existsSync(fullPath)) {
      return res.status(404).json({
        success: false,
        message: '图片文件不存在'
      });
    }
    
    // 检查文件大小
    const stats = fs.statSync(fullPath);
    const fileSizeInMB = stats.size / (1024 * 1024);
    if (fileSizeInMB > 10) {
      return res.status(400).json({
        success: false,
        message: `文件大小(${fileSizeInMB.toFixed(2)}MB)超过处理限制(10MB)`
      });
    }
    
    // 处理图片
    const processedImagePath = await imageUtils.enhanceDocument(fullPath);
    
    res.status(200).json({
      success: true,
      message: '图片处理成功',
      data: {
        processedImagePath: processedImagePath.replace(path.join(__dirname, '../public'), ''),
        fullPath: `${req.protocol}://${req.get('host')}${processedImagePath.replace(path.join(__dirname, '../public'), '')}`
      }
    });
  } catch (error) {
    console.error('处理图片出错:', error);
    res.status(500).json({
      success: false,
      message: '处理图片失败',
      error: error.message
    });
  }
};

// 合并多张图片为长图
exports.mergeImages = async (req, res) => {
  try {
    const { imagePaths } = req.body;
    
    if (!imagePaths || !Array.isArray(imagePaths) || imagePaths.length === 0) {
      return res.status(400).json({
        success: false,
        message: '缺少有效的图片路径数组'
      });
    }
    
    // 限制图片数量
    const MAX_IMAGES = 10;
    if (imagePaths.length > MAX_IMAGES) {
      return res.status(400).json({
        success: false,
        message: `图片数量(${imagePaths.length})超过限制(${MAX_IMAGES})`
      });
    }
    
    // 获取完整的文件路径
    const fullPaths = imagePaths.map(p => path.join(__dirname, '../public', p.replace(/^\//, '')));
    
    // 检查所有文件是否存在
    for (const filePath of fullPaths) {
      if (!fs.existsSync(filePath)) {
        return res.status(404).json({
          success: false,
          message: `图片文件不存在: ${filePath}`
        });
      }
    }
    
    // 检查文件总大小
    let totalSizeInMB = 0;
    for (const filePath of fullPaths) {
      const stats = fs.statSync(filePath);
      totalSizeInMB += stats.size / (1024 * 1024);
    }
    
    if (totalSizeInMB > 20) {
      return res.status(400).json({
        success: false,
        message: `文件总大小(${totalSizeInMB.toFixed(2)}MB)超过处理限制(20MB)`
      });
    }
    
    // 合并图片
    const mergedImagePath = await imageUtils.mergeImages(fullPaths);
    
    res.status(200).json({
      success: true,
      message: '图片合并成功',
      data: {
        mergedImagePath: mergedImagePath.replace(path.join(__dirname, '../public'), ''),
        fullPath: `${req.protocol}://${req.get('host')}${mergedImagePath.replace(path.join(__dirname, '../public'), '')}`
      }
    });
  } catch (error) {
    console.error('合并图片出错:', error);
    res.status(500).json({
      success: false,
      message: '合并图片失败',
      error: error.message
    });
  }
};

// 生成PDF
exports.generatePDF = async (req, res) => {
  try {
    const { imagePaths, title } = req.body;
    
    if (!imagePaths || !Array.isArray(imagePaths) || imagePaths.length === 0) {
      return res.status(400).json({
        success: false,
        message: '缺少有效的图片路径数组'
      });
    }
    
    // 限制图片数量
    const MAX_IMAGES = 20;
    if (imagePaths.length > MAX_IMAGES) {
      return res.status(400).json({
        success: false,
        message: `图片数量(${imagePaths.length})超过限制(${MAX_IMAGES})`
      });
    }
    
    // 获取完整的文件路径
    const fullPaths = imagePaths.map(p => path.join(__dirname, '../public', p.replace(/^\//, '')));
    
    // 检查所有文件是否存在
    for (const filePath of fullPaths) {
      if (!fs.existsSync(filePath)) {
        return res.status(404).json({
          success: false,
          message: `图片文件不存在: ${filePath}`
        });
      }
    }
    
    // 检查文件总大小
    let totalSizeInMB = 0;
    for (const filePath of fullPaths) {
      const stats = fs.statSync(filePath);
      totalSizeInMB += stats.size / (1024 * 1024);
    }
    
    if (totalSizeInMB > 30) {
      return res.status(400).json({
        success: false,
        message: `文件总大小(${totalSizeInMB.toFixed(2)}MB)超过处理限制(30MB)`
      });
    }
    
    // 生成PDF
    const pdfPath = await imageUtils.generatePDF(fullPaths, title || '文档');
    
    res.status(200).json({
      success: true,
      message: 'PDF生成成功',
      data: {
        pdfPath: pdfPath.replace(path.join(__dirname, '../public'), ''),
        fullPath: `${req.protocol}://${req.get('host')}${pdfPath.replace(path.join(__dirname, '../public'), '')}`
      }
    });
  } catch (error) {
    console.error('生成PDF出错:', error);
    res.status(500).json({
      success: false,
      message: '生成PDF失败',
      error: error.message
    });
  }
};